from fastapi.encoders import jsonable_encoder
from sqlalchemy import select

from common.utils import set_attrs
from exception.customException import UserExistsException
from model.admin import AdminModel, Admin
from model import Session
from model.account import  AccountRegister


class registerService:
    @staticmethod
    def register(account: AccountRegister,db_session: Session):
        query = select(Admin).where(Admin.username == account.username)
        exists_test : AdminModel = db_session.execute(query).scalars().first()
        if exists_test:
            raise UserExistsException("该账户已存在")

        new_user = Admin()
        set_attrs(new_user, jsonable_encoder(account))
        if new_user.username is None:
            new_user.username = account.username


        db_session.add(new_user)
        db_session.commit()
        return new_user